<?php

namespace App\Api\Three\ShopA;

/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use App\Api\ChannelApi;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;

// use function GuzzleHttp\json_decode;
//  湖南电信接口
class HuNanTelecom extends ChannelApi
{
    protected $model;
    protected $appKey = '';
    protected $url = '';
    protected $secret = '';
    protected $channel = '';
    protected $config = [];
    protected $HTTPOK = 1; //检查接口返回的数据 返回1 代表返回正确
    protected $root;
    protected $log;
    protected $isTrue = true;
    protected $return_message = '';
    protected $accessToken;
    protected $pname;

    public function __construct($url = '', $str = '')
    {
        // 南沙
        $this->pname = 'HuNanTelecom';
        $this->log = new Logger('HuNanTelecom');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/HuNanTelecom.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->url = $url;
        $this->accessToken = 'ZWMyOTI0MWE1OTdhYjM0YTA1NGFkNmNmNDMxZTkzYTE=';
    }
    public function sentPost($method, $data)
    {
        $data = [
            'access_token' => $this->accessToken,
            'method' => $method,
            'version' => '1.0',
            'content' => $data
        ];
        $headers = [
            'application/json; charset=UTF-8',
        ];
        var_dump($data);
        $res = $this->sendBefare($this->url, $data, $headers);
        return $res;
    }
    public function checkOrder($array = [])
    {
        $method = 'chk.ordercheck.InternetCardQualifica';
        $data = [
            'cartNo' => $array['pay_identity'],
            'serviceOrderSource' => '',
            'serviceOrderSalesNumber' => '',
            'buyerName' => $array['pay_name'],
            'mobilePhone' => $array['pay_phone'],
            'receiverName' => $array['pay_name'],
            'receiverProv' => $array['post_province'],
            'receiverCity' => $array['post_city'],
            'receiverDistrict' => $array['post_area'],
            'receiverAdress' => $array['post_address']
        ];
        $res = $this->sentPost($method, $data);
        var_dump($res);
    }
    public  function getStatusCode($status)
    {
        $str = 'qita@qita@qiaoqiao';
        switch ($status) {
            case 1:
                $str = 'zb@qita@qiaoqiao01';
                break;
            case 6:
                $str = 'zb@qita@qiaoqiao02';
                break;
        }
        return $str;
    }
    // 提交上游
    public function orderSubmit($array = [])
    {
        // // 暂时先不发送 返回成功
        // 组装提交数据
        $method = 'syn.orderinfo.SynJdServiceOrder';
        $time = date('Y-m-d H:i:s');
        $getStatusCode = $this->getStatusCode($array['source']);
        $data = [
            'serviceOrderOutOrderId' => $array['orderno'],
            'serviceOrderSubmitTime' => $time,
            'serviceOrderCusName' => $array['pay_name'],
            'serviceOrderCusCardNo' => $array['pay_identity'],
            'serviceOrderCusContactPhone' => $array['pay_phone'],
            'serviceOrderSalesNumber' => $array[''],
            'serviceOrderReceiverName' => $array['pay_name'],
            'serviceOrderReceiverProvCode' => $array['post_province'],
            'serviceOrderReceiverCityCode' => $array['post_city'],
            'serviceOrderReceiverDistrictCode' => $array['post_area'],
            'serviceOrderReceiverAddress' => $array['post_address'],
            'serviceOrderType' => '', // 订单业务类型
            'serviceOrderSource' => '', // 订单渠道
            'serviceOrderCpsRefereePeople' => $getStatusCode,
            'serviceOrderRefereePeople' => 'CPS2',
            ''
        ];

        $headers = [
            'Content-Type:application/json;charset=utf-8',
            'X-Sign:' . $this->getSign($strArr),
        ];
        // var_dump($this->getSign($strArr));
        $url = $this->url . $method;
        $res =  $this->sendBefare($url, $strArr, $headers);
        $this->log->info('参数:' . ($strArr) . '返回的参数:' . $res);
        // if (is_string($res)) {
        //     $res = json_decode($res, true);
        // }
        if (!empty($res)) {
            return $this->returnMsg(200, '提交成功', ['order_id' => !empty($res) ? $res : '']);
        }
        return $this->returnMsg(100, '提交失败', ['order_id' => !empty($res) ? $res : '']);
    }
    // 不同套餐 设置的参数不一样
    public function setData($data)
    {
    }
    // 查询订单 查询
    public function queryOrderStatus($array = [])
    {
    }
    // 处理数据 将数据处理成统一格式
    public function queryOneOrder($array = [])
    {
        $res = $this->queryOrderStatus($array);
        if (empty($res['data'])) {
            return $this->returnMsg(100, '数据为空');
        }
        if (empty($res['data']['data']['q'])) {
            return $this->returnMsg(101, '未查询到数据');
        }
        $getData = $res['data']['data']['q'][0];
        $data = [
            'id' => $getData['uid'],
            'sup_order' => $getData['订单编码'],
            'created_at' => date('Y-m-d H:i:s', strtotime($getData['下单时间'])),
            'order_desc' => $getData['订单当前状态']['订单状态名称'],
            'order_desc_at' => date('Y-m-d H:i:s', strtotime($getData['订单当前状态']['订单当前状态|状态更新时间'])),
            'order_num' => $getData['订单来源2']['订单来源单号'],
            'pagename' => $getData['订购产品']['产品名称'],
            'express_company' => $getData['订单配送方式']['配送公司'],
            'express_number' => !empty($getData['订单配送方式']['配送公司']) ? $getData['订单配送方式']['配送公司'] : '',
            'province' => !empty($getData['收件人地址'][0]['省']) ? $getData['收件人地址'][0]['省'] : '',
            'city' => !empty($getData['收件人地址'][0]['市']) ? $getData['收件人地址'][0]['市'] : '',
            'area' => !empty($getData['收件人地址'][0]['区']) ? $getData['收件人地址'][0]['区'] : '',
            'address' => !empty($getData['收件人地址'][0]['详细地址']) ? $getData['收件人地址'][0]['详细地址'] : '',
        ];
        return $this->returnMsg(200, '查询成功', [$data]);
    }
    public function sendBefare($url, $data, $headers, $isPost = 1)
    {
        // return 1212222222222;
        $curl = curl_init(); // 启动一个CURL会话
        // if (!empty($isPost) || $isPost != 1) {
        //     $url = $url . '?data=' . urlencode($data);
        // }
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        if ($isPost == 1) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        if (curl_error($curl)) {
            //请求失败，返回错误信息
            $res =  curl_error($curl);
            var_dump($res);
            return $res;
        }
        curl_close($curl); // 关闭CURL会话

        return $result;
    }
    public function sendBefareGet($url, $data, $headers)
    {
        $curl = curl_init(); // 启动一个CURL会话
        $url = $url . '?data=' . urlencode($data);
        // var_dump($url, 666666666);
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        // curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        $result = curl_exec($curl); // 执行操作
        // var_dump($result, 111111111);
        curl_close($curl); // 关闭CURL会话
        return $result;
    }
    public function getSign($str)
    {
        if (is_array($str)) {
            $str = json_encode($str, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }
        $strs = strtolower(md5($str));
        $getPKey = $this->getPublicKey();
        $key = openssl_pkey_get_public($getPKey);
        $return = openssl_public_encrypt($strs, $crypted, $key);
        if (!$return) {
            return '';
        }
        return base64_encode($crypted);
    }
    public function getPublicKey()
    {
        $str = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAok8DnvM2OBwtzNoJb4nA
jn4lgCkSxLyRw5lLiUfsi+40h00CGAC1arvbinTTbtrSnm4YDYlaJwveiOeDKdk0
f2Yglb/8loEbNTqb1OqNxUeM1wYLRBXvAkkZ5fZllajWzFMkoNU/JQ4+T8sMATxm
1d1XRcgM6zlgVwX6siDoLZ5Dm23CTS7SXhyMLtS9cgLefHcOckPQyXoB/IJqb0K1
P0Sk0PE1OSRzpsI9JVzhsSW164fwYpxEbygj9O9JAmAszixwItt2j5zLJ6zRnK3R
OrcAVMN/vpXTN2dCLGZXQrsTK9sAWASzIWTiQRzmnwxsQY7y4u2h+k41n8Z5tw03
wwIDAQAB
-----END PUBLIC KEY-----";
        return $str;
    }
}
